package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;


    @Value("${fileServerUrl}")
    private String fileServerUrl;


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        try {
            if(multipartFile == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String path = fastDFSClientUtil.uploadFile(multipartFile);

            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(path);
            wmMaterial.setIsCollection((short)0);
            WmUser wmUser = WmThreadLocalUtils.getUser();
            if (wmUser!=null){
                wmMaterial.setUserId(wmUser.getId());
            }
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);

            wmMaterial.setUrl(fileServerUrl.concat(path));
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId = null;
        if (wmUser!=null){
            userId =  wmUser.getId();
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId,userId);
        if (dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page page = new Page(dto.getPage(),dto.getSize());
        IPage result = page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        List<WmMaterial> records = result.getRecords();
        records = records.stream().map(a->{
            a.setUrl(fileServerUrl.concat(a.getUrl()));
            return a;
        }).collect(Collectors.toList());
        responseResult.setData(records);
        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        try {
            //1.检查参数
            if(id == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            WmMaterial wmMaterial = getById(id);
            if(wmMaterial == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //2.判断当前图片是否问引用
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
            Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
            if(count > 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前图片被引用");
            }
            //3.删除fastdfs中的图片
            //http://192.168.58.138/group1/M00/00/00/11111.jpg
            //group1/M00/00/00/11111.jpg
            String fileId = wmMaterial.getUrl().replace(fileServerUrl, "");
            fastDFSClientUtil.delFile(fileId);
            //4.删除数据库中的图片
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {
        if (id==null || status==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = null;
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser!=null){
            userId = wmUser.getId();
        }
        UpdateWrapper<WmMaterial> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(WmMaterial::getIsCollection,status).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        boolean b = this.update(updateWrapper);
        if (b){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
